import 'dart:io';

import 'package:elevator/get/intl_keys.dart';
import 'package:flutter/cupertino.dart';
import 'package:ftpconnect/ftpConnect.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';

import '../../../../../../../db/error_data.dart';

class OperateLogic extends GetxController {

  late ErrorData errorData;
  var msg = "".obs;
  var imgPath = "".obs;

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
    loadImg();
  }

  String getCpu() {
    String result = errorData.fErrorCode!.replaceAll(RegExp(r'[^a-zA-Z]'),'');
    return result;
  }

  String getError() {
    String result = errorData.fErrorCode!.replaceAll(RegExp(r'[^0-9]'),'');
    return result;
  }

  loadImg() async {
      String toDownloadFile = "img/errorCode/${errorData.fErrorCode}.jpg";
      debugPrint('OperateLogic:准备下载图片：$toDownloadFile');
      msg.value = IntlKeys.startLoadingImage.tr;
      Directory directory = await getTemporaryDirectory();
      String path = '${directory.path}${Platform.pathSeparator}img${Platform.pathSeparator}errorCode';
      String localFile = "$path${Platform.pathSeparator}${errorData.fErrorCode}.jpg";
      var fileExist = File(localFile).existsSync();
      if(fileExist){
        debugPrint('OperateLogic:图片已经存在，开始加载本地图片');
        msg.value = IntlKeys.imageLoading.tr;
        imgPath.value = localFile;
        return;
      }
      var dir = Directory(path);
      var exist = dir.existsSync();
      if (exist) {
        debugPrint('OperateLogic:当前文件夹已经存在');
        doDownload( toDownloadFile, localFile);
      } else {
        var result = await dir.create(recursive :true)
            .then((value) => doDownload(toDownloadFile,localFile))
            .catchError((onError){
          msg.value = IntlKeys.imageLoadWithWrongPath.tr;
          debugPrint('OperateLogic:$onError');
        });
        debugPrint('OperateLogic:result:$result');
      }


  }

  doDownload(String toDownloadFile,String localFile){
    msg.value = IntlKeys.imageDownloading.tr;

    downloadFile(toDownloadFile,localFile)
        .then((value) => {
      debugPrint("OperateLogic:$value"),
      msg.value = IntlKeys.imageDownloadToLoad.tr,
      imgPath.value = localFile
    })
        .onError((error, stackTrace) => {
      debugPrint("OperateLogic:$error"),
      msg.value = IntlKeys.imageDownloadingErrorTips.tr,
    }
    );
  }

  Future<bool> downloadFile(String toDownloadFile,String localFile) async{
    FTPConnect ftpConnect = FTPConnect('36.141.45.30',port: 58021,user:'admin', pass:'adminemqx123');
    String fileName = toDownloadFile;
    debugPrint("OperateLogic:start connect");
    await ftpConnect.connect();
    bool res = await ftpConnect.downloadFileWithRetry(fileName, File(localFile));
    debugPrint("OperateLogic:end connect:res$res");
    await ftpConnect.disconnect();
    debugPrint("OperateLogic:ftpConnect.disconnect");
    return res;
  }

}
